package org.example.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.User;
import org.example.exception.ErrorEnum;
import org.example.exception.ServiceException;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器:{}", request.getRequestURI());
        // 检测请求方式是不是预检请求
        String method = request.getMethod();
        if (HttpMethod.OPTIONS.matches(method)) {
            // 如果是预检请求, 直接放行
            return true;
        }
        // 判断session中的user有没有失效
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            throw new ServiceException(ErrorEnum.LOGIN_EXPIRATION);
        }
        return true;
    }
}
